//
//  RSAuthManage.m
//  RSTools
//
//  Created by thinkjoy on 2017/10/16.
//  Copyright © 2017年 杜瑞胜. All rights reserved.
//

#import "RSAuthManage.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>

@implementation RSAuthManage

+ (void)judgeDeviceAuthByAuthType:(RSAuthManageType)type block:(void(^)(BOOL isAuth))authBlock
{
    switch (type) {
        case RSAuthManageType_Camera:
        {
            [RSAuthManage judgeCaptureDeviceCameraAuth:^(BOOL isAuth) {
                if (authBlock) {
                    authBlock(isAuth);
                }
            }];
        }
            break;
        case RSAuthManageType_Library:
        {
            [RSAuthManage judgeCaptureDeviceLibraryAuth:^(BOOL isAuth) {
                if (authBlock) {
                    authBlock(isAuth);
                }
            }];
        }
        default:
            break;
    }
}

#pragma mark - 相机权限检测
+ (void)judgeCaptureDeviceCameraAuth:(void(^)(BOOL isAuth))authBlock
{
    // 1、 获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusNotDetermined) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        if (authBlock) {
                            authBlock(YES);
                        }
                    });
                    
                    // 用户第一次同意了访问相机权限
                    NSLog(@"用户第一次同意了访问相机权限 - - %@", [NSThread currentThread]);
                } else {
                    if (authBlock) {
                        authBlock(NO);
                    }
                    
                    // 用户第一次拒绝了访问相机权限
                    NSLog(@"用户第一次拒绝了访问相机权限 - - %@", [NSThread currentThread]);
                }
            }];
        } else if (status == AVAuthorizationStatusAuthorized) { // 用户允许当前应用访问相机
            if (authBlock) {
                authBlock(YES);
            }
        } else if (status == AVAuthorizationStatusDenied) { // 用户拒绝当前应用访问相机
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:@"还没有开启相机权限,请在系统设置中开启" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"暂不" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                if (authBlock) {
                    authBlock(NO);
                }
            }];
            UIAlertAction * actionSet    =   [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //跳转到设置界面
                if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
                    if ([[[UIDevice currentDevice] systemVersion] floatValue]<10) {

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
#pragma clang diagnostic pop
                    }else{
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                    }
                }
            }];
            [alertC addAction:actionCancel];
            [alertC addAction:actionSet];
            
            [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertC animated:YES completion:nil];
            
        } else if (status == AVAuthorizationStatusRestricted) {
            NSLog(@"因为系统原因, 无法访问相册");
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:@"无权限访问相机" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                if (authBlock) {
                    authBlock(NO);
                }
            }];
            
            [alertC addAction:alertA];
            [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertC animated:YES completion:nil];
        }
    } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            if (authBlock) {
                authBlock(NO);
            }
        }];
        
        [alertC addAction:alertA];
        [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertC animated:YES completion:nil];
    }
}

#pragma mark - 相册权限检测
+ (void)judgeCaptureDeviceLibraryAuth:(void(^)(BOOL isAuth))authBlock
{
    // 判断授权状态
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusNotDetermined) { // 用户还没有做出选择
        // 弹框请求用户授权
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) { // 用户第一次同意了访问相册权限
                
                dispatch_sync(dispatch_get_main_queue(), ^{
                    if (authBlock) {
                        authBlock(YES);
                    }
                });
                
                NSLog(@"用户第一次同意了访问相册权限 - - %@", [NSThread currentThread]);
                
            } else { // 用户第一次拒绝了访问相机权限
                if (authBlock) {
                    authBlock(NO);
                }
                
                NSLog(@"用户第一次拒绝了访问相册权限 - - %@", [NSThread currentThread]);
            }
        }];
    } else if (status == PHAuthorizationStatusAuthorized) { // 用户允许当前应用访问相册
        if (authBlock) {
            authBlock(YES);
        }
    } else if (status == PHAuthorizationStatusDenied) { // 用户拒绝当前应用访问相册
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:@"还没有开启相册权限,请在系统设置中开启" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"暂不" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            if (authBlock) {
                authBlock(NO);
            }
        }];
        UIAlertAction * actionSet    =   [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //跳转到设置界面
            if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
                if ([[[UIDevice currentDevice] systemVersion] floatValue]<10) {
                    
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
#pragma clang diagnostic pop
                }else{
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                }
            }
        }];
        [alertC addAction:actionCancel];
        [alertC addAction:actionSet];
        
        [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertC animated:YES completion:nil];
    } else if (status == PHAuthorizationStatusRestricted) {
        NSLog(@"由于系统原因, 无法访问相册");
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:@"无权限访问相机" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            if (authBlock) {
                authBlock(NO);
            }
        }];
        
        [alertC addAction:alertA];
        [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertC animated:YES completion:nil];
    }
}
@end
